home *** CD-ROM | disk | FTP | other *** search
- Path: news.mel.aone.net.au!usenet
- From: clyde@hitech.com.au (Clyde Smith-Stubbs)
- Newsgroups: comp.lang.c
- Subject: Re: read/write integers to files
- Date: Thu, 07 Mar 1996 10:47:08 GMT
- Organization: HI-TECH Software
- Message-ID: <313ebdba.694734775@news.bne.aone.net.au>
- References: <313EBF65.4E82@www.inia.net.au>
- Reply-To: clyde@hitech.com.au
- NNTP-Posting-Host: skyhawk.hitech.com.au
- X-Newsreader: Forte Agent .99d/32.182
-
- On Thu, 07 Mar 1996 20:50:13 +1000, Jason Collins
- <jason@www.inia.net.au> wrote:
-
- >My problem is that I'm trying to write a program that will read an integer from the file
- >count.dat, increment the integer then write it back to count.dat. I have provided the listing so
- >that you can all tell me what I'm doing wrong.
-
- Here's your problem:
-
- > filePtr=fopen("count.dat", "ab");
- > fscanf(filePtr, "%d", &ctr);
-
- You declared ctr as a char, but you're using a %d scanf format - you
- must pass a pointer to an int if you use %d. So make ctr an int and
- you should be right - I can't see any other obvious errors. However
- you could make it simpler: try this:
-
- main()
- {
- FILE * fp;
- int x;
-
- fp = fopen("count.dat", "r+");
- if(!fp) {
- perror("count.dat");
- exit(1);
- }
- x = 0;
- fscanf(fp, "%d", &x);
- x++;
- rewind(fp);
- fprintf(fp, "%d", x);
- fclose(fp);
- }
-
- Note the use of the "r+" format to open a file for reading and
- writing. The rewind() call allows you to switch from reading
- to writing.
-
-
- > fclose(filePtr);
- >
- > ctr++;
- >
- > filePtr=fopen("count.dat", "wb");
- > fprintf(filePtr, "%d", ctr);
- > fclose(filePtr);
- >}
-
- ----
- Clyde Smith-Stubbs | HI-TECH Software, | Voice: +61 7 3300 5011
- clyde@hitech.com.au | P.O. Box 103, Alderley, | Fax: +61 7 3300 5246
- http://www.hitech.com.au | QLD, 4051, AUSTRALIA. | BBS: +61 7 3300 5235
- ----------------------------------------------------------------------------
- FREE! Download our shareware (FREE for noncommercial use) MS-DOS C Compiler!
- Point your Web browser at http://www.hitech.com.au/
-